/*
* Copyright (c) 2008 michiyasu wada
* http://www.seyself.com/
* 
* Distributed under The MIT License.
* [http://www.opensource.org/licenses/mit-license.php]
*/

import flash.display.BitmapData;
import flash.geom.Matrix;
import flash.geom.Transform;

class com.seyself.utils.BitmapUtil
{
    
    
    public static function preview( bitmap:BitmapData , x:Number , y:Number ):MovieClip
    {
        var preview:MovieClip = _root["__bitmapPreviewStage__"];
        if( !preview ){
            preview = _root.createEmptyMovieClip( "__bitmapPreviewStage__" , 26780 );
        }
        var dep:Number = preview.getNextHighestDepth();
        var mc:MovieClip = preview.createEmptyMovieClip( "prev_"+dep , dep );
        mc.attachBitmap( bitmap , 10 , "auto" , false );
        mc._x = x || 0;
        mc._y = y || 0;
        return mc;
    }
    
    public static function attachBitmap( target:MovieClip, bitmap:BitmapData , smoothing:Boolean ):MovieClip
    {
        smoothing = smoothing == true;
        if ( !target.bitmap ) target.bitmap = 
            target.createEmptyMovieClip( "bitmap" , target.getNextHighestDepth() );
        target.bitmap.attachBitmap( bitmap , target.bitmap.getNextHighestDepth() , "auto" , smoothing );
        return target.bitmap;
    }
    
    public static function swapBitmap( target:MovieClip ):MovieClip
    {
        var bitmap:BitmapData = capture( target );
        var rect:Object = target.getBounds( target );
        var depth:Number = target.getDepth();
        var transform:Transform = target.transform;
        var name:String = target._name;
        var scaleX:Number = target._xscale;
        var scaleY:Number = target._yscale;
        var rotate:Number = target._rotation;
        var nd:Number = target._parent.getNextHighestDepth();
        if ( nd > 1048575 ) nd = 38196;
        target.swapDepths( nd );
        var image:MovieClip = target._parent.createEmptyMovieClip( name , depth );
        attachBitmap( image, bitmap, true );
        image.bitmap._x = rect.xMin;
        image.bitmap._y = rect.yMin;
        image.transform = transform;
        image._xscale = scaleX;
        image._yscale = scaleY;
        image._rotation = rotate;
        target.removeMovieClip();
        return image;
    }
    
    public static function capture( target:MovieClip ):BitmapData
    {
        var rect:Object = target.getBounds( target );
        var width:Number = rect.xMax - rect.xMin;
        var height:Number = rect.yMax - rect.yMin;
        var bitmap:BitmapData = new BitmapData( width , height, true, 0x000000 );
        var matrix:Matrix = new Matrix();
        matrix.translate( -rect.xMin , -rect.yMin );
        bitmap.draw( target , matrix );
        return bitmap;
    }
    
}


